package com.derek.ucd;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;


import com.derek.ucd.smartonfacebook.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;


public class smartonfacebookActivity extends Activity {
	
	String[] allcategories;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        ListView list = (ListView) findViewById(R.id.listViewCategories);         
        
        
        //TODO: Needs to be ASyncTask for final version
        try {
            Class strictModeClass=Class.forName("android.os.StrictMode");
            Class strictModeThreadPolicyClass=Class.forName("android.os.StrictMode$ThreadPolicy");
            Object laxPolicy = strictModeThreadPolicyClass.getField("LAX").get(null);
            Method method_setThreadPolicy = strictModeClass.getMethod(
                    "setThreadPolicy", strictModeThreadPolicyClass );
            method_setThreadPolicy.invoke(null,laxPolicy);
        } catch (Exception e) {

        }
        
        // TODO: Allow language change 
        String APIRoot = "https://en.wikiquote.org/w/api.php?";
        String QueryCategories = "action=query&list=allcategories&format=json&aclimit=50&acmin=250";
        	
        // Create the httpclient
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(APIRoot + QueryCategories ); 
        HttpResponse response;
        // Declare a return string
        String returnString = null;

        try {        	 
            response = httpclient.execute(httpget);
             if(response.getStatusLine().getStatusCode() == 200){
                // Connection was established. Get the content. 
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    // A Simple JSON Response Read
                    InputStream instream = entity.getContent();
                    // Load the requested page converted to a string into a JSONObject.
                    JSONObject tmp = new JSONObject(convertStreamToString(instream));
                    // Close the stream.
                    instream.close();

					String query = tmp.getString("query");
					JSONObject queryJSON = new JSONObject(query);
                    JSONArray allCategoriesJSON = queryJSON.getJSONArray("allcategories");

                    allcategories = new String[allCategoriesJSON.length()];
                    for(int i = 0; i < allCategoriesJSON.length(); i++) {
                    	allcategories[i] = allCategoriesJSON.getString(i).substring(6, (allCategoriesJSON.getString(i)).length()-2);
                    }
                          
                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, allcategories);
                     // Assign adapter to ListView
                    list.setAdapter(adapter);
                }
                
                list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {               
            		
            			Intent i = new Intent(smartonfacebookActivity.this, Pages.class);
            			i.putExtra("category", allcategories[position]);
            			startActivity(i);

            	}
            	});
           
            }
            else {
                // code here for a response other than 200.  A response 200 means the web page was OK
                // Other codes include 404 - not found, 301 - redirect etc...
                // Display the response line.
                returnString = "Unable to load page - " + response.getStatusLine();
            }
        }
         catch (Exception e) {
 			// TODO Auto-generated catch block
 			e.printStackTrace();
 		}    
    }
    
    private static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
 
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}